package top.codecrab.eblog.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.codecrab.eblog.common.response.R;
import top.codecrab.eblog.entity.Post;
import top.codecrab.eblog.entity.UserCollection;
import top.codecrab.eblog.utils.ShiroUtil;

/**
 * 收藏控制器
 *
 * @author 王刚
 * @since 2022年03月18日 20:49
 */
@Controller
public class CollectionController extends BaseController {

    @ResponseBody
    @PostMapping("/collection/find")
    public R collectionFind(Long pid) {
        long count = collectionService.count(
            new QueryWrapper<UserCollection>()
                .eq("user_id", ShiroUtil.getProfileId())
                .eq("post_id", pid)
        );

        return R.ok().put("collection", count > 0);
    }

    @ResponseBody
    @PostMapping("/collection/remove")
    public R collectionRemove(Long pid) {
        boolean remove = collectionService.remove(
            new QueryWrapper<UserCollection>()
                .eq("user_id", ShiroUtil.getProfileId())
                .eq("post_id", pid)
        );

        return remove ? R.ok() : R.fail("取消收藏失败，文章状态异常");
    }

    @ResponseBody
    @PostMapping("/collection/add")
    public R collectionAdd(Long pid) {
        Post post = postService.getOne(
            new QueryWrapper<Post>()
                .eq("id", pid)
                .ge("status", 1)
        );

        Assert.notNull(post, "文章已被删除或被封禁");

        UserCollection collection = new UserCollection();
        collection.setPostId(pid);
        collection.setPostUserId(post.getUserId());
        collection.setUserId(ShiroUtil.getProfileId());
        collection.setStatus(1);
        //执行保存
        boolean save = collectionService.save(collection);
        return save ? R.ok() : R.fail("收藏失败，文章状态异常");
    }

}
